import React, { useRef, useImperativeHandle, forwardRef, useState } from 'react';
import { Button } from 'antd';


// 子组件
const ChildComponent = forwardRef((props, ref) => {

  const [value, setValue] = useState(0);

  const showMessage = () => {
    console.log('这是子组件的方法');
  };

  useImperativeHandle(ref, () => ({
    showMessage,

    // 可通过方法获取到 状态值
    getValue: () => value,
  }));

  return <div>子组件</div>;
});

// 父组件
const ParentComponent = () => {
  const childRef = useRef(null);

  const callChildMethod = () => {
    if (childRef.current) {
      childRef.current.showMessage();
    }
  };

  return (
    <div>
      <ChildComponent ref={childRef} />
      <button onClick={callChildMethod}>调用子组件方法</button>
    </div>
  );
};

export default ParentComponent;
